<?php

class EntiteDAO extends DAO{


	function getById($id){
		try
		{
			$id =Validator::escapeSql($id);
			$query="select * from ENTITE where id=$id;";
			 
			$statement=$this->pdo->query($query);
			$array_obj=$statement->fetchAll(PDO::FETCH_OBJ);
			$propDAO = $this->factory->getProprieteDAO();
			$typeEntiteDAO = $this->factory->getTypeEntiteDAO();
			$thebean = null;
			foreach($array_obj as $Bean){
				$thebean = new Entite((int)$Bean->ID);
				$thebean->setTypeEntite($typeEntiteDAO->getById((int)$Bean->TYPE_ENTITE_ID));
				$thebean->setProprietes($propDAO->getAllByEntite($thebean));
			}
		}
		catch(Exception $e)     {
			throw $e;
		}

		return $thebean;
	}
	function remove($Bean){
		try{
			$propValDAO = $this->factory->getProprieteValueDAO();
			foreach ($Bean->getProprietes() as $Prop){
				foreach ($Prop->getValues as $val){
					$propValDAO->remove($val);
				}
			}
			$query="delete from ENTITE where id='".Validator::escapeSql($Bean->getId())."';";
			$this->pdo->exec($query);
			$bool=true;
		}catch(Exception $e)    {
			$bool=false;
		}
		return $bool;

	}
	function update($Bean){
		try{
			$propValDAO = $this->factory->getProprieteValueDAO();
			foreach ($Bean->getProprietes() as $Prop){
				foreach ($Prop->getValues as $val){
					$propValDAO->update($val);
				}
			}

			$query = "update ENTITE set type_entite_id=".Validator::escapeSql($Bean->getTypeEntite()->getId())." where id=".Validator::escapeSql($Bean->getId()).";";
			$this->pdo->exec($query);
			$bool=true;
		}
		catch(Exception $e)     {
			$bool=false;
			 
		}
		return $bool;
	}
	function add($Bean){
		 
		try{
			 
			if (is_null($Bean->getId())){
				$propValDAO = $this->factory->getProprieteValueDAO();
				$thebean = null;
				foreach ($Bean->getProprietes() as $Prop){
					foreach ($Prop->getValues as $val){
						$propValDAO->add($val);
					}
				}
				$insertQuery = "insert into ENTITE (Type_entite_id) values (".Validator::escapeSql($Bean->getTypeEntite()->getId()).");";
				$this->pdo->exec($insertQuery);
				$thebean = $this->getById((int)$this->pdo->lastInsertId());
			}
		}catch(Exception $e)    {$this->pdo->message;}
		return $thebean;
	}

	function All(){
		try
		{

			$BeanArray = array();
			$query="select * from ENTITE;";
			$statement=$this->pdo->query($query);
			$array_obj=$statement->fetchAll(PDO::FETCH_OBJ);
			$thebean = null;
			foreach($array_obj as $Bean){
				$thebean = $this->getById((int)$Bean->ID);
				array_push($BeanArray,$thebean);
			}
				
		}
		catch(Exception $e)     {
			throw $e;
		}

		return $BeanArray;

	}

}
?>